package com.mansoor.app.islamicnames.db;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import com.mansoor.app.islamicnames.beans.Name;
import com.mansoor.app.islamicnames.util.AppConstant;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by IntelliJ IDEA.
 * User: Mansoor
 * Date: Oct 20, 2009
 * Time: 10:17:38 PM
 * To change this template use File | Settings | File Templates.
 */
public class NamesDao
{
    private SQLiteDatabase db;

    public NamesDao(Context context)
    {
        db = new NameDBHelper(context).getWritableDatabase();
    }

    public void storeFavorate(Name name)
    {
        if (!isExist(name.getName()))
        {
            ContentValues contentValues = new ContentValues();
            contentValues.put("name", name.getName());
            contentValues.put("gender", name.getGender());
            contentValues.put("meaning", name.getMeaning());
            db.insert(AppConstant.NAMES_TABLE, null, contentValues);
        }

    }

    public List<Name> retrieveFavorate()
    {
        List<Name> names = new ArrayList<Name>();

        Cursor c = null;
        try
        {
            c = this.db.query(AppConstant.NAMES_TABLE, AppConstant.COLUMNS, null, null, null, null, null);
            int numRows = c.getCount();
            c.moveToFirst();
            for (int i = 0; i < numRows; ++i)
            {
                Name name = new Name();
                name.setName(c.getString(0));
                name.setGender(c.getString(1));
                name.setMeaning(c.getString(2));
                c.moveToNext();
                names.add(name);
            }
        }
        finally
        {
            if (c != null && !c.isClosed())
            {
                c.close();
            }
        }
        return names;
    }

    private boolean isExist(String name)
    {

        boolean result=false;
        Cursor c = this.db.query(true, AppConstant.NAMES_TABLE, AppConstant.COLUMNS, "name = '" + name + "'", null, null, null, null, null);
        if(c.getCount() > 0)
        {
            c.moveToFirst();
            result = c.getString(0).equals(name);
        }

        return result;

    }

    public void delete(String name)
    {
        this.db.delete(AppConstant.NAMES_TABLE, "name='" + name + "'", null);
    }

    public void cleanup()
    {
        if (this.db != null)
        {
            this.db.close();
            this.db = null;
        }
    }


}
